package com.controller;

import com.google.gson.Gson;
import com.pojo.Enterprise;
import com.pojo.User;
import com.service.IEnterpriseService;
import com.service.IUserService;
import com.service.impl.EnterpriseServiceImpl;
import com.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/login/*")
public class UserController extends HttpServlet {
    private IUserService ius = new UserServiceImpl();
    private IEnterpriseService ies = new EnterpriseServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String requestURI = request.getRequestURI();

        // 找到最后一个"/"的位置并加1，得到方法名的起始位置
        int index = requestURI.lastIndexOf("/") + 1;

        // 从URI中提取方法名，例如：queryByPid
        String mName = requestURI.substring(index);

        // 获取当前类的Class对象
        Class cla = this.getClass();
        Method method = null;
        try {
            // 通过反射获取指定方法名的Method对象
            // 该方法需要接受HttpServletRequest和HttpServletResponse两个参数
            method = cla.getMethod(mName, HttpServletRequest.class, HttpServletResponse.class);
            response.setContentType("application/json;charset=utf-8");
            request.setCharacterEncoding("utf-8");
            // 使用反射调用获取到的方法，传入当前对象和请求、响应参数
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            // 如果找不到对应的方法，打印异常堆栈
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // 如果方法不可访问，打印异常堆栈
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // 如果方法调用抛出异常，打印异常堆栈
            e.printStackTrace();
        }
    }

    //登录页面
    public void userlogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        try {
            // 3. 后端参数校验（防止前端校验被绕过）
            if (account == null || account.trim().isEmpty()) {
                response.getWriter().println(new Gson().toJson("账号不能为空"));
                return;
            }
            if (password == null || password.trim().isEmpty()) {
                response.getWriter().println(new Gson().toJson("密码不能为空"));
                return;
            }

            // 4. 调用登录逻辑
            boolean loginSuccess = ius.login(account, password);
            if (loginSuccess) {
                // 5. 设置Session（添加过期时间，如30分钟）
                request.getSession().setAttribute("loginUser", account);
                request.getSession().setMaxInactiveInterval(30 * 60); // 单位：秒
                response.getWriter().println(new Gson().toJson("登录成功")); // 与前端判断一致，不带感叹号
            } else {
                response.getWriter().println(new Gson().toJson("登录失败，账号或密码错误"));
            }
        } catch (Exception e) {
            // 6. 异常处理（返回友好提示）
            e.printStackTrace(); // 日志记录异常
            response.getWriter().println(new Gson().toJson("登录失败，系统异常，请稍后重试"));
        }

    }

    //根据账号获取手机号
    public void getAdminPhone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String account = request.getParameter("account");
        String phone = ius.getAdminPhoneByAccount(account);
        response.getWriter().println(new Gson().toJson(phone));
    }

//    验证管理员姓名和身份证号
    public void verify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

        String account = request.getParameter("account");
        String idcardName = request.getParameter("idcardName");
        String idcardNo = request.getParameter("idcardNo");
        boolean b = ius.verifyAdminInfo(account, idcardName, idcardNo);
        response.getWriter().println(new Gson().toJson(b));
    }

    // 管理员认证接口
    public void adminCertification(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        // 从session获取当前登录用户账号
        String account = (String) request.getSession().getAttribute("loginUser");
        String idcardName = request.getParameter("idcardName");
        String idcardNo = request.getParameter("idcardNo");
        
        try {
            // 检查用户是否已登录
            if (account == null || account.trim().isEmpty()) {
                response.getWriter().println(new Gson().toJson("用户未登录，请先登录"));
                return;
            }
            
            // 参数校验
            if (idcardName == null || idcardName.trim().isEmpty()) {
                response.getWriter().println(new Gson().toJson("管理员姓名不能为空"));
                return;
            }
            if (idcardNo == null || idcardNo.trim().isEmpty()) {
                response.getWriter().println(new Gson().toJson("身份证号不能为空"));
                return;
            }

            // 格式校验
            if (!ius.validateAdminName(idcardName.trim())) {
                response.getWriter().println(new Gson().toJson("管理员姓名格式错误，请输入不超过5个汉字"));
                return;
            }
            if (!ius.validateIdCardNo(idcardNo.trim())) {
                response.getWriter().println(new Gson().toJson("身份证号格式错误，请输入18位数字，第18位可为X"));
                return;
            }

            // 验证管理员信息是否与数据库中的信息匹配
            boolean isMatched = ius.verifyAdminInfo(account, idcardName.trim(), idcardNo.trim());
            if (isMatched) {
                response.getWriter().println(new Gson().toJson("管理员认证成功，信息验证通过"));
            } else {
                response.getWriter().println(new Gson().toJson("管理员认证失败，姓名或身份证号与系统记录不符"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("系统异常，请稍后重试"));
        }
    }

    // 更新管理员认证信息
    public void updateAdminInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String account = request.getParameter("account");
        String idcardName = request.getParameter("idcardName");
        String idcardNo = request.getParameter("idcardNo");
        
        try {
            // 参数校验
            if (account == null || account.trim().isEmpty()) {
                response.getWriter().println(new Gson().toJson("账号不能为空"));
                return;
            }
            if (idcardName == null || idcardName.trim().isEmpty()) {
                response.getWriter().println(new Gson().toJson("管理员姓名不能为空"));
                return;
            }
            if (idcardNo == null || idcardNo.trim().isEmpty()) {
                response.getWriter().println(new Gson().toJson("身份证号不能为空"));
                return;
            }

            // 格式校验
            if (!ius.validateAdminName(idcardName)) {
                response.getWriter().println(new Gson().toJson("管理员姓名格式错误，请输入不超过5个汉字"));
                return;
            }
            if (!ius.validateIdCardNo(idcardNo)) {
                response.getWriter().println(new Gson().toJson("身份证号格式错误，请输入18位数字，第18位可为X"));
                return;
            }

            // 更新管理员信息
            boolean updateSuccess = ius.updateAdminInfo(account, idcardName, idcardNo);
            if (updateSuccess) {
                response.getWriter().println(new Gson().toJson("管理员认证信息更新成功"));
            } else {
                response.getWriter().println(new Gson().toJson("管理员认证信息更新失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("系统异常，请稍后重试"));
        }
    }

    // 获取当前登录用户的完整信息
    public void getCurrentUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String account = (String) request.getSession().getAttribute("loginUser");
        
        if (account == null) {
            response.getWriter().println(new Gson().toJson("用户未登录"));
            return;
        }
        
        try {
            User user = ius.getUserByAccount(account);
            if (user != null) {
                // 为了安全，不返回密码信息
                user.setPassword(null);
                response.getWriter().println(new Gson().toJson(user));
            } else {
                response.getWriter().println(new Gson().toJson("用户信息不存在"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("获取用户信息失败"));
        }
    }

    /**
     * 获取当前用户关联的企业信息
     */
    public void getCurrentUserEnterprise(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 从session中获取当前用户账号
            String account = (String) request.getSession().getAttribute("loginUser");
            
            if (account == null) {
                response.getWriter().println(new Gson().toJson("用户未登录"));
                return;
            }
            
            // 获取用户信息
            User user = ius.getUserByAccount(account);
            if (user == null) {
                response.getWriter().println(new Gson().toJson("用户不存在"));
                return;
            }
            
            // 获取用户关联的企业信息
            Integer enterpriseId = user.getEnterpriseId();
            if (enterpriseId == null) {
                response.getWriter().println(new Gson().toJson("用户未关联企业"));
                return;
            }
            
            // 根据enterpriseId获取企业详细信息
            Enterprise enterprise = ies.getEnterpriseById(enterpriseId);
            if (enterprise == null) {
                response.getWriter().println(new Gson().toJson("企业信息不存在"));
                return;
            }
            
            // 返回企业信息
            response.getWriter().println(new Gson().toJson(enterprise));
            
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(new Gson().toJson("获取企业信息失败"));
        }
    }

}
